package com.andy.blog.admin.service.impl;

import com.andy.blog.admin.dto.login.HomeInfoDTO;
import com.andy.blog.admin.dto.login.LoginDTO;
import com.andy.blog.admin.service.ConfigBusService;
import com.andy.blog.admin.service.LoginBusService;
import com.andy.blog.common.constant.BaseConstants;
import com.andy.blog.common.constant.BlogInfoConstants;
import com.andy.blog.common.constant.CacheConstants;
import com.andy.blog.common.constant.UserConstants;
import com.andy.blog.common.core.domain.model.LoginUser;
import com.andy.blog.common.core.redis.RedisCache;
import com.andy.blog.common.enums.ClientTypeEnum;
import com.andy.blog.common.enums.DeleteTypeEnum;
import com.andy.blog.common.exception.BlogServiceException;
import com.andy.blog.common.reponse.BlogResultCode;
import com.andy.blog.common.utils.DateUtils;
import com.andy.blog.common.utils.MessageUtils;
import com.andy.blog.common.utils.ip.IpUtils;
import com.andy.blog.common.utils.sign.RsaUtils;
import com.andy.blog.dal.domain.SysUserDO;
import com.andy.blog.dal.service.ArticleDalService;
import com.andy.blog.dal.service.SysUserDalService;
import com.andy.blog.dal.vo.ArticleVO;
import com.andy.blog.dal.vo.SysLoginLogVO;
import com.andy.blog.dal.vo.SysUserVO;
import com.andy.blog.framework.manager.AsyncManager;
import com.andy.blog.framework.manager.factory.AsyncFactory;
import com.andy.blog.framework.security.context.AuthenticationContextHolder;
import com.andy.blog.framework.web.service.TokenService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by andy on 2023-04-15 15:00
 */
@Service
public class LoginBusServiceImpl implements LoginBusService {


    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SysUserDalService userService;

    @Resource
    private ConfigBusService configBusService;

    @Resource
    private ArticleDalService articleDalService;

    @Override
    public Map<String, String> login(LoginDTO loginDTO) {

        String passWord = RsaUtils.decryptByPrivateKey(loginDTO.getPassword());

        if (ClientTypeEnum.MANAGE.getCode().equals(loginDTO.getClientType())) {
            // 验证码校验
            validateCaptcha(loginDTO.getUsername(), loginDTO.getCode(), loginDTO.getUuid(), loginDTO.getClientType());
        }
        // 登录前置校验
        loginPreCheck(loginDTO.getUsername(), passWord, loginDTO.getClientType());
        // 用户验证
        Authentication authentication;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginDTO.getUsername(), passWord);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用 UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLoginLog(
                        SysLoginLogVO.builder()
                                .userName(loginDTO.getUsername())
                                .status(BaseConstants.LOGIN_FAIL)
                                .clientType(loginDTO.getClientType())
                                .msg(MessageUtils.message("user.password.not.match"))
                                .build())
                );
                throw new BlogServiceException(BlogResultCode.BLOG_000005);
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLoginLog(
                        SysLoginLogVO.builder()
                                .userName(loginDTO.getUsername())
                                .status(BaseConstants.LOGIN_FAIL)
                                .clientType(loginDTO.getClientType())
                                .msg(e.getMessage())
                                .build()));
                throw new BlogServiceException(e.getMessage());
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }

        AsyncManager.me().execute(AsyncFactory.recordLoginLog(
                SysLoginLogVO.builder().userName(loginDTO.getUsername()).status(BaseConstants.LOGIN_SUCCESS)
                        .clientType(loginDTO.getClientType()).msg(MessageUtils.message("user.login.success")).build()));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        recordLoginInfo(loginUser.getId());

        // 生成token
        String token = tokenService.createToken(loginUser);

        // 访问量+1
        redisCache.incr(BlogInfoConstants.ADMIN_VIEW_COUNT, 1);

        Map<String, String> map = new HashMap<>();
        map.put(BaseConstants.TOKEN, token);
        return map;
    }

    @Override
    public HomeInfoDTO getHome() {
        // 后台访问量
        Integer viewCount = redisCache.getCacheObject(BlogInfoConstants.ADMIN_VIEW_COUNT);
        // 文章数
        Long articleCount = articleDalService.selectArticleCount(ArticleVO.builder().isDeleted(DeleteTypeEnum.DELETE_N.getCode()).build());
        // 用户数
        List<SysUserDO> sysUserDOS = userService.selectUserList(SysUserVO.builder().build());

        return HomeInfoDTO.builder().viewCount(viewCount).articleCount(articleCount).userCount(sysUserDOS.size()).build();
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     */
    public void validateCaptcha(String username, String code, String uuid, String clientType) {
        boolean captchaEnabled = configBusService.selectCaptchaEnabled();

        if (captchaEnabled) {
            SysLoginLogVO sysLoginLogVO = new SysLoginLogVO();
            sysLoginLogVO.setClientType(clientType);
            sysLoginLogVO.setUserName(username);
            sysLoginLogVO.setStatus(BaseConstants.LOGIN_FAIL);

            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
            String captcha = redisCache.getCacheObject(verifyKey);
            redisCache.deleteObject(verifyKey);
            if (captcha == null) {
                sysLoginLogVO.setMsg(MessageUtils.message("user.jcaptcha.expire"));
                AsyncManager.me().execute(AsyncFactory.recordLoginLog(sysLoginLogVO));
                throw new BlogServiceException(BlogResultCode.BLOG_000003);
            }
            if (!code.equalsIgnoreCase(captcha)) {
                sysLoginLogVO.setMsg(MessageUtils.message("user.jcaptcha.error"));
                AsyncManager.me().execute(AsyncFactory.recordLoginLog(sysLoginLogVO));
                throw new BlogServiceException(BlogResultCode.BLOG_000004);
            }
        }
    }

    /**
     * 登录前置校验
     *
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password, String clientType) {
        SysLoginLogVO sysLoginLogVO = new SysLoginLogVO();
        sysLoginLogVO.setClientType(clientType);
        sysLoginLogVO.setUserName(username);

        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password)) {
            sysLoginLogVO.setStatus(BaseConstants.LOGIN_FAIL);
            sysLoginLogVO.setMsg(MessageUtils.message("not.null"));
            AsyncManager.me().execute(AsyncFactory.recordLoginLog(sysLoginLogVO));
            throw new BlogServiceException(BlogResultCode.BLOG_000002);
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            sysLoginLogVO.setStatus(BaseConstants.LOGIN_FAIL);
            sysLoginLogVO.setMsg(MessageUtils.message("user.password.not.match"));
            AsyncManager.me().execute(AsyncFactory.recordLoginLog(sysLoginLogVO));
            throw new BlogServiceException(BlogResultCode.BLOG_000005);
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            sysLoginLogVO.setStatus(BaseConstants.LOGIN_FAIL);
            sysLoginLogVO.setMsg(MessageUtils.message("user.password.not.match"));
            AsyncManager.me().execute(AsyncFactory.recordLoginLog(sysLoginLogVO));
            throw new BlogServiceException(BlogResultCode.BLOG_000005);
        }
        // IP黑名单校验
        String blackStr = configBusService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddress())) {
            sysLoginLogVO.setStatus(BaseConstants.LOGIN_FAIL);
            sysLoginLogVO.setMsg(MessageUtils.message("login.blocked"));
            AsyncManager.me().execute(AsyncFactory.recordLoginLog(sysLoginLogVO));
            throw new BlogServiceException(BlogResultCode.BLOG_000007);
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId) {
        SysUserVO sysUser = new SysUserVO();
        sysUser.setId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddress());
        sysUser.setLoginDate(DateUtils.getCurrentDate());
        userService.updateUserProfile(sysUser);
    }
}
